<?php

/**
 * 检测用户是否登录
 * @return integer 0-未登录，大于0-当前登录用户ID
 * @author 唐小虎 <1731050423@qq.com>
 */
function is_login(){
    $user = session('user_auth');
    if (empty($user)) {
        return 0;
    } else {
        return session('user_auth_sign') == data_auth_sign($user) ? $user['uid'] : 0;
    }
}
/**
 * 检测当前用户是否为管理员
 * @return boolean true-管理员，false-非管理员
 * @author 唐小虎 <1731050423@qq.com>
 */
function is_administrator($uid = null){
    $uid = is_null($uid) ? is_login() : $uid;
    return $uid && (intval($uid) === config('USER_ADMINISTRATOR'));
}
if (!function_exists('data_auth_sign')) {
    /**
     * 数据签名认证
     * @param  array  $data 被认证的数据
     * @return string       签名
     * @author 唐小虎 <1731050423@qq.com>
     */
    function data_auth_sign($data) {
        //数据类型检测
        if(!is_array($data)){
            $data = (array)$data;
        }
        ksort($data); //排序
        $code = http_build_query($data); //url编码并生成query字符串
        $sign = sha1($code); //生成签名
        return $sign;
    }
}
if (!function_exists('get_client_ip')) {
    /**
     * 获取客户端IP地址
     * @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @param bool $adv 是否进行高级模式获取（有可能被伪装）
     * @return mixed
     */
    function get_client_ip($type = 0, $adv = false) {
        $type       =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if($adv){
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos    =   array_search('unknown',$arr);
                if(false !== $pos) unset($arr[$pos]);
                $ip     =   trim($arr[0]);
            }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip     =   $_SERVER['HTTP_CLIENT_IP'];
            }elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip     =   $_SERVER['REMOTE_ADDR'];
            }
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
}


/**
 * 记录行为日志，并执行该行为的规则
 * @param string $action 行为标识
 * @param string $model 触发行为的模型名
 * @param int $record_id 触发行为的记录id
 * @param int $user_id 执行行为的用户id
 * @return boolean
 * @author 唐小虎 <1731050423@qq.com>
 */
function action_log($action = null, $model = null, $record_id = null, $user_id = null){

    //参数检查
    if(empty($action) || empty($model) || empty($record_id)){
        return '参数不能为空';
    }
    if(empty($user_id)){
        $user_id = is_login();
    }

    //查询行为,判断是否执行
    $action_info = model('app\admin\model\Action')->getByName($action);
    if($action_info['status'] != 1){
        return '该行为被禁用或删除';
    }

    //插入行为日志
    $data['action_id']      =   $action_info['id'];
    $data['user_id']        =   $user_id;
    $data['action_ip']      =   get_client_ip();
    $data['model']          =   $model;
    $data['record_id']      =   $record_id;
    $data['create_time']    =   time();

    //解析日志规则,生成日志备注
    if(!empty($action_info['log'])){
        if(preg_match_all('/\[(\S+?)\]/', $action_info['log'], $match)){
            $log['user']    =   $user_id;
            $log['record']  =   $record_id;
            $log['model']   =   $model;
            $log['time']    =   time();
            $log['data']    =   array('user'=>$user_id,'model'=>$model,'record'=>$record_id,'time'=>time());
            foreach ($match[1] as $value){
                $param = explode('|', $value);
                if(isset($param[1])){
                    $replace[] = call_user_func($param[1],$log[$param[0]]);
                }else{
                    $replace[] = $log[$param[0]];
                }
            }
            $data['remark'] =   str_replace($match[0], $replace, $action_info['log']);
        }else{
            $data['remark'] =   $action_info['log'];
        }
    }else{
        //未定义日志规则，记录操作url
        $data['remark']     =   '操作url：'.$_SERVER['REQUEST_URI'];
    }
    model('app\admin\model\ActionLog')->create($data);
}


/**
 * 根据ID获取角色名称
 */
function get_role_name($id){
    return $id > 0 ? model('admin/Role')->where('id',$id)->value('title') : '无';
}

/**
 * 根据ID获取文章分类名称
 */
function get_articleCate_name($id){
    return $id > 0 ? model('admin/articleCate')->where('id',$id)->value('title') : '顶级分类';
}

function get_region_name($id){
    return $id > 0 ? model('admin/region')->where('id',$id)->value('title') : '顶级地区';
}

function get_deriver_name($id){
    return $id > 0 ? model('admin/deriver')->where('deriver_id',$id)->value('realname') : '无';
}

function get_user_head_pic($user_id){
    $head_pic = $user_id > 0 ? model('admin/user')->where('user_id',$user_id)->value('head_pic') : 0;
    return get_thumb($head_pic);
}

function get_user_name($user_id){
    $nickname = $user_id > 0 ? model('admin/user')->where('user_id',$user_id)->value('nickname') : '无';
    return $nickname;
}

function get_user_mobile($user_id){
    $nickname = $user_id > 0 ? model('admin/user')->where('user_id',$user_id)->value('mobile') : '无';
    return $nickname;
}

function get_deriver_mobile($id){
    return $id > 0 ? model('admin/deriver')->where('deriver_id',$id)->value('mobile') : '无';
}

function get_car_code($deriver_id){
    return $deriver_id > 0 ? model('admin/car')->where('deriver_id',$deriver_id)->value('car_code') : '无';
}

function get_route_name($id){
    return $id > 0 ? model('admin/route')->where('id',$id)->value('name') : '无';
}